import React, { useState, useEffect } from 'react';
import { Card, Typography, Alert, Space, Button, List, Tag, Divider } from 'antd';
import { LinkOutlined, ApiOutlined, InfoCircleOutlined } from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;

const TrackerStatus: React.FC = () => {
  const [trackerUrl, setTrackerUrl] = useState('');

  useEffect(() => {
    // 使用后端服务器地址构建tracker URL
    const protocol = window.location.protocol;
    const host = window.location.hostname;
    const port = window.location.port;
    setTrackerUrl(`${protocol}//${host}:${port}/api/announce`);
  }, []);

  const trackerInfo = [
    {
      title: 'Announce URL',
      value: trackerUrl,
      description: 'BitTorrent客户端用于汇报状态的地址'
    },
    {
      title: 'Scrape URL', 
      value: trackerUrl.replace('/announce', '/scrape'),
      description: '获取种子统计信息的地址'
    }
  ];

  const announceParams = [
    { 
      name: 'info_hash', 
      required: true, 
      description: '种子的20字节SHA1哈希值。必须使用原始字节进行URL编码，而不是十六进制字符串。例如：如果info_hash是"abc..."，应该用encodeURIComponent(String.fromCharCode(0xab, 0xc...))而不是直接发送"abc..."' 
    },
    { 
      name: 'peer_id', 
      required: true, 
      description: '客户端生成的20字节标识符。同样需要使用原始字节URL编码' 
    },
    { name: 'port', required: true, description: '客户端监听端口' },
    { name: 'uploaded', required: true, description: '已上传字节数' },
    { name: 'downloaded', required: true, description: '已下载字节数' },
    { name: 'left', required: true, description: '剩余字节数' },
    { name: 'passkey', required: true, description: '用户密钥（用于身份验证）' },
    { name: 'event', required: false, description: '事件类型：started, completed, stopped' },
    { name: 'compact', required: false, description: '是否使用紧凑格式（默认1）' },
    { name: 'numwant', required: false, description: '期望返回的Peer数量（默认50）' }
  ];

  const exampleCode = `
  // 示例：如何正确编码info_hash
  const infoHashHex = "0123456789abcdef0123456789abcdef01234567"; // 40位十六进制字符串
  const infoHashBytes = new Uint8Array(20);
  for (let i = 0; i < 40; i += 2) {
    infoHashBytes[i/2] = parseInt(infoHashHex.substr(i, 2), 16);
  }
  const infoHashStr = String.fromCharCode.apply(null, infoHashBytes);
  const encodedInfoHash = encodeURIComponent(infoHashStr);
  `;

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      // 这里可以添加复制成功的提示
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>Tracker 状态</Title>
      
      <Card title="Tracker 地址">
        <List
          itemLayout="vertical"
          dataSource={trackerInfo}
          renderItem={item => (
            <List.Item>
              <Title level={4}>{item.title}</Title>
              <Space direction="vertical">
                <Text copyable>{item.value}</Text>
                <Text type="secondary">{item.description}</Text>
              </Space>
            </List.Item>
          )}
        />
      </Card>

      <Divider />

      <Card title="请求参数说明">
        <Alert
          message="重要提示"
          description="info_hash和peer_id必须使用原始字节进行URL编码，而不是直接发送十六进制字符串。请参考下方的示例代码。"
          type="warning"
          showIcon
          style={{ marginBottom: '20px' }}
        />
        
        <List
          itemLayout="vertical"
          dataSource={announceParams}
          renderItem={item => (
            <List.Item>
              <Space direction="vertical">
                <Space>
                  <Text strong>{item.name}</Text>
                  {item.required && <Tag color="red">必需</Tag>}
                </Space>
                <Text type="secondary">{item.description}</Text>
              </Space>
            </List.Item>
          )}
        />

        <Divider />

        <Title level={4}>编码示例</Title>
        <pre style={{ 
          background: '#f6f8fa', 
          padding: '16px', 
          borderRadius: '6px',
          overflow: 'auto' 
        }}>
          <code>{exampleCode}</code>
        </pre>
      </Card>
    </div>
  );
};

export default TrackerStatus; 